import 'package:enterprise_v6_app/app/components/custom_app_bar.dart';
import 'package:enterprise_v6_app/app/components/custom_modele/custom_bottom_sheet.dart';
import 'package:enterprise_v6_app/app/components/dialog/custom_general_dialog.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/ext/widget_extension.dart';
import 'package:enterprise_v6_app/app/modules/application/education/quiz/model.dart';
import 'package:enterprise_v6_app/app/modules/application/education/quiz/quiz_controller.dart';
import 'package:enterprise_v6_app/app/modules/application/education/quiz/widget.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';

const _blue = Color(0xFF5C6DFF);

/// 如何传入参数
/// ```dart
/// Get.toNamed(Routes.educationQuiz, arguments: QuizConfig(
///     type: QuizType.test,
///     topics: <QuizTopic>[
///       QuizTopic(
///         question: '请问根据《工保险条例》规定，下列有关工伤保险费的缴纳的说法中，不正确的是',
///         answers: ['水剂'],
///         options: ['水剂', 'BBBBBB', 'CCCCccc', 'DDdddDD'],
///         score: 10,
///       ),
///     ],
///     leftSeconds: 60,
///     textbookId: '教材ID',
///     planId: '计划ID',
///     surveys: GetDetailByIdEntity(),
///   )
/// );
/// ```
class EducationQuizView extends StatelessWidget {
  EducationQuizView({super.key});

  final quizConfig = (Get.arguments as QuizConfig?) ??
      QuizConfig(
        type: QuizType.dailyLearn,
        topics: <QuizTopic>[],
      );

  late final controller = Get.put(EducationQuizController(quizConfig));

  @override
  Widget build(BuildContext context) {
    return GetBuilder(
      init: controller,
      builder: (_) {
        return WillPopScope(
          child: Scaffold(
            appBar: CustomAppBar(
              titleText: quizConfig.type.title,
            ),
            backgroundColor: const Color(0xFFF5F5F6),
            body: _buildBody(),
            bottomSheet: SafeArea(child: _buildBottom()),
          ),
          onWillPop: () async {
            // if (controller.isFinished) {
            //   return true;
            // }
            return await Get.dialog<bool>(
                  const CustomGeneralDialog(
                    content: '确认退出吗？',
                  ),
                ) ??
                false;
          },
        );
      },
    );
  }

  /// 主要
  Widget _buildBody() {
    final quiz = GestureDetector(
      onHorizontalDragEnd: (detail) => controller.onSlide(
        detail.velocity.pixelsPerSecond.dx > 177,
        detail.velocity.pixelsPerSecond.dx < -177,
      ),
      child: _buildQuiz(),
    );
    return ListView(
      children: [
        AppGaps.vGap16,
        _buildTop(),
        AppGaps.vGap16,
        quiz,
        if (controller.isFinished) _buildQuizExplain(),
        AppGaps.vGap50,
      ],
    );
  }

  /// 题目顶部 倒计时 / 字体大小切换
  Widget _buildTop() {
    final left = _buildTopLeft();
    return Padding(
      padding: EdgeInsets.symmetric(
        horizontal: 18.w,
      ),
      child: Container(
        width: 343.w,
        height: 48.w,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10.w),
          color: Colors.white,
        ),
        padding: EdgeInsets.symmetric(horizontal: 16.w),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            if (left != null) left,
            _buildTextSizeSwitch(),
          ],
        ),
      ),
    );
  }

  /// 倒计时 / 题目对错指示器
  Widget? _buildTopLeft() {
    final leftTime = controller.leftTime;
    if (controller.config.type.watchTime && !controller.config.isFinished) {
      return Row(
        children: [
          Stack(
            alignment: Alignment.bottomCenter,
            children: [
              Container(
                width: 48.w,
                height: 5.w,
                decoration: BoxDecoration(
                    color: Colors.blue,
                    borderRadius: BorderRadius.circular(4.w),
                    gradient: LinearGradient(
                      colors: [
                        Colors.blue.shade100,
                        Colors.blue.shade500,
                        Colors.blue,
                      ],
                    )),
              ),
              Text(
                '倒计时',
                style: TextStyle(
                  fontSize: 16.w,
                  color: const Color(0xFF333333),
                ),
              )
            ],
          ),
          AppGaps.hGap6,
          _buildTopTimeSingle(leftTime.hours),
          _buildTopTimeDivider(),
          _buildTopTimeSingle(leftTime.minutes),
          _buildTopTimeDivider(),
          _buildTopTimeSingle(leftTime.seconds)
        ],
      );
    }
    return controller.config.isFinished ? QuizWidgets.statusIndicator : null;
  }

  /// 倒计时 单个数字
  Widget _buildTopTimeSingle(int time) {
    return Container(
      width: 20.w,
      height: 20.w,
      alignment: Alignment.center,
      decoration: BoxDecoration(color: _blue, borderRadius: BorderRadius.circular(4.w)),
      child: Text(
        time.toString().padLeft(2, '0'),
        style: TextStyle(fontSize: 14.w, color: Colors.white),
      ),
    );
  }

  /// 倒计时 分割线
  Widget _buildTopTimeDivider() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 2.w),
      child: Text(
        ':',
        style: TextStyle(fontSize: 18.w, color: Colors.blue),
      ),
    );
  }

  /// 字体大小切换
  Widget _buildTextSizeSwitch() {
    final child = Row(
      crossAxisAlignment: CrossAxisAlignment.end,
      children: QuizTextSize.values.map(_buildTextSizeSwitchSingle).toList(),
    );
    return Container(
      padding: EdgeInsets.all(1.w),
      decoration: BoxDecoration(border: Border.all(color: _blue, width: 1.w), borderRadius: BorderRadius.circular(4.w)),
      child: child,
    );
  }

  /// 字体大小切换 单个按钮
  Widget _buildTextSizeSwitchSingle(QuizTextSize size) {
    final current = controller.textSize.value == size;
    return InkWell(
      onTap: () {
        if (!current) {
          controller.textSize.value = size;
          controller.update();
        }
      },
      child: Container(
        width: 28.w,
        height: 28.w,
        decoration: BoxDecoration(
          color: current ? _blue : Colors.white,
          borderRadius: BorderRadius.circular(4.w),
        ),
        alignment: Alignment.center,
        child: Text(
          'Aa',
          style: TextStyle(
            fontSize: (size.toInt - 6).w,
            color: current ? Colors.white : _blue,
          ),
        ),
      ),
    );
  }

  /// 题目 主要
  Widget _buildQuiz() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Stack(
        children: [
          Container(
            height: 20.w,
            decoration: BoxDecoration(
              color: _blue,
              borderRadius: BorderRadius.circular(10.w),
            ),
          ),
          Container(
            margin: const EdgeInsets.only(top: 2),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(10.w),
            ),
            child: _buildQuizContent(),
          ),
          if (!controller.isFinished)
            Positioned(
              bottom: 0,
              left: 0,
              right: 0,
              child: Container(
                decoration: BoxDecoration(color: Colors.white, border: Border(top: BorderSide(color: const Color(0x33587DF5), width: 1.w))),
                padding: EdgeInsets.symmetric(vertical: 14.w),
                child: Row(
                  mainAxisSize: MainAxisSize.max,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const Text('答题卡'),
                    AppGaps.hGap10,
                    SizedBox(
                      width: 16.w,
                      height: 16.w,
                      child: Image.asset(AppImages.icon_blue_paper_history),
                    ),
                  ],
                ).clickOnce(() {
                  CustomBottom.show<int>(
                    child: ConstrainedBox(
                      constraints: BoxConstraints(
                        maxHeight: (controller.quizs.length ~/ 5 + 1) * 72.w,
                      ),
                      child: GridView.builder(
                        physics: const NeverScrollableScrollPhysics(),
                        itemCount: controller.quizs.length,
                        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 5),
                        itemBuilder: (_, index) {
                          final item = controller.quizs[index];
                          return Container(
                            height: 36.w,
                            width: 36.w,
                            margin: EdgeInsets.all(18.w),
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              color: item.isAnswered ? _blue : const Color(0x1A5C6DFF),
                              borderRadius: BorderRadius.circular(17.w),
                            ),
                            child: Text(
                              (index + 1).toString(),
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                color: item.isAnswered ? Colors.white : const Color(0xFF5C6DFF),
                                fontSize: 16.w,
                              ),
                            ),
                          ).clickOnce(
                            () {
                              Get.back();
                              controller.currentQuizIdx = index;
                              controller.update();
                            },
                          );
                        },
                      ),
                    ),
                    title: '答题卡',
                  );
                }),
              ),
            ),
        ],
      ),
    );
  }

  /// 题目 内容
  Widget _buildQuizContent() {
    final quiz = controller.currentQuiz;
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 14.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildQuizTitle(),
          AppGaps.vGap20,
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 16.w),
            child: Text(
              quiz.question,
              style: TextStyle(fontSize: controller.textSize.value.toInt.w),
            ),
          ),
          AppGaps.vGap10,
          ...List.generate(quiz.options.length, _buildQuizOption),
          // 防止被答题卡挡住
          AppGaps.vGap50,
        ],
      ),
    );
  }

  /// 题目 标题
  Widget _buildQuizTitle() {
    final scoreStr = () {
      final score = controller.currentQuiz.score;
      if (score == 0) return '';
      return '($score分)';
    }();
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Container(
            decoration: BoxDecoration(
              color: const Color(0x1A5C6DFF),
              borderRadius: BorderRadius.circular(4.w),
            ),
            padding: EdgeInsets.symmetric(vertical: 4.w, horizontal: 12.w),
            child: Text(
              '${controller.currentQuiz.answers.length == 1 ? "单" : "多"}选题$scoreStr',
              style: TextStyle(
                color: _blue,
                fontSize: 14.w,
              ),
            ),
          ),
          Row(
            children: [
              Text(
                (controller.currentQuizIdx + 1).toString(),
                style: TextStyle(
                  color: const Color(0xFF495061),
                  fontSize: 16.w,
                ),
              ),
              Text(
                ' / ${controller.config.wrongCount ?? controller.quizs.length}',
                style: TextStyle(
                  color: const Color(0xFFA0A7B5),
                  fontSize: 16.w,
                ),
              ),
            ],
          )
        ],
      ),
    );
  }

  /// 判断题目选项该显示什么颜色
  Color? judgeOptionColor(int idx, bool isSelected) {
    if (controller.isFinished) {
      if (controller.currentQuiz.answers.contains(idx)) {
        return const Color.fromARGB(26, 114, 255, 92);
      }
      if (isSelected) {
        return const Color(0x1AFD6B6B);
      }
      return null;
    }
    if (isSelected) return const Color(0x1A5C6DFF);
    return null;
  }

  /// 题目 选项
  Widget _buildQuizOption(int idx) {
    final isSelected = controller.currentQuiz.isSelectedIdx(idx);
    final quiz = controller.currentQuiz;
    final option = quiz.options[idx];
    final color = judgeOptionColor(idx, isSelected);

    return Container(
      decoration: BoxDecoration(
        color: color,
        border: color != null ? Border(left: BorderSide(color: color.withOpacity(1), width: 2.w)) : null,
      ),
      margin: EdgeInsets.symmetric(vertical: 2.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            children: [
              AppGaps.hGap20,
              SizedBox(
                width: 270.w,
                child: Text(
                  '${controller.idx2Str(idx)}、 $option',
                  style: TextStyle(
                    fontSize: controller.textSize.value.toInt.w,
                    color: Colors.black,
                  ),
                  softWrap: true,
                ),
              ),
            ],
          ),
          controller.currentQuiz.isMulti
              ? Checkbox(
                  value: isSelected,
                  onChanged: (_) => controller.selectOption(option),
                  overlayColor: MaterialStateProperty.all(color),
                )
              : Radio(
                  value: option,
                  groupValue: isSelected ? option : null,
                  onChanged: (_) => controller.selectOption(option),
                ),
        ],
      ),
    ).clickOnce(() {
      controller.selectOption(option);
    });
  }

  /// 题目 底部解析
  Widget _buildQuizExplain() {
    final explain = controller.currentQuiz.explain;
    return Container(
      width: 375.w,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10.w),
        color: Colors.white,
      ),
      margin: EdgeInsets.all(13.w),
      padding: EdgeInsets.all(17.w),
      child: Column(
        children: [
          Container(
            decoration: BoxDecoration(color: const Color(0x1A5C6DFF), borderRadius: BorderRadius.circular(7.w)),
            padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 14.w),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  children: [
                    Text(
                      '正确答案：',
                      style: TextStyle(
                        fontSize: 14.w,
                        color: const Color(0xFF495061),
                      ),
                    ),
                    Text(
                      controller.currentQuiz.answerStr,
                      style: const TextStyle(color: Colors.green),
                    ),
                  ],
                ),
                Row(
                  children: [
                    Text(
                      '您的答案：',
                      style: TextStyle(
                        fontSize: 14.w,
                        color: const Color(0xFF495061),
                      ),
                    ),
                    Text(
                      controller.currentQuiz.selectedStr,
                      style: TextStyle(color: controller.currentQuiz.isAnswerRight ? Colors.green : Colors.red),
                    ),
                  ],
                ),
              ],
            ),
          ),
          if (explain != null) AppGaps.vGap20,
          if (explain != null)
            Row(
              children: [
                SvgPicture.asset(AppImages.icon_title),
                AppGaps.hGap6,
                Text(
                  '答案解析',
                  style: TextStyle(fontSize: 14.w),
                ),
              ],
            ),
          if (explain != null) AppGaps.vGap10,
          if (explain != null)
            Text(
              explain,
              style: TextStyle(fontSize: 12.w, color: AppColors.font_color_black),
            )
        ],
      ),
    );
  }

  /// 底部的按钮
  Widget _buildBottom() {
    return Container(
      width: 375.w,
      height: 50.w,
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: const Color(0x0D000000),
            offset: Offset(0, -3.w),
            blurRadius: 2.w,
            spreadRadius: 0,
          ),
        ],
      ),
      child: Padding(
        padding: EdgeInsets.symmetric(vertical: 5.w, horizontal: 16.w),
        child: InkWell(
          onTap: () async {
            if (controller.isFinished) {
              Get.toNamed(AppRoutes.quizResultPage);
              return;
            }
            final unanswered = controller.config.notAnsweredCount;
            var resume = unanswered == 0;
            if (!resume) {
              resume = await Get.dialog<bool>(
                    CustomGeneralDialog(
                      content: '剩余$unanswered题未答，确认交卷吗？',
                    ),
                  ) ??
                  false;
            }
            if (!resume) return;
            controller.config.onFinish();
          },
          child: Container(
            padding: EdgeInsets.symmetric(vertical: 9.w),
            decoration: BoxDecoration(
              color: _blue,
              borderRadius: BorderRadius.circular(44.w),
            ),
            alignment: Alignment.center,
            child: Text(
              controller.isFinished ? '查看统计' : '交卷',
              style: TextStyle(
                fontSize: 16.w,
                color: Colors.white,
              ),
            ),
          ),
        ),
      ),
    );
  }
}
